/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.boot.tasks;

import org.internna.iwebjtracker.model.TrackerUser;
import org.internna.iwebmvc.boot.StartupTask;
import org.internna.iwebmvc.dao.DAO;
import org.internna.iwebmvc.dao.SecurityDAO;
import org.internna.iwebmvc.model.Sex;
import org.internna.iwebmvc.model.security.UserImpl;
import org.internna.iwebmvc.utils.Assert;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Creates the root admin for the application.
 *
 * @author Jose Noheda
 * @since 1.0
 */
@Transactional
public final class CreateTrackerAdministratorStartupTask implements StartupTask {

    private DAO dao;
    private String rootUserName;
    private SecurityDAO securityDAO;

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param dao a not null instance
     */
    @Required public void setDao(DAO dao) {
        Assert.notNull(dao);
        this.dao = dao;
    }

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param rootUserName a not empty string
     */
    @Required public void setRootUserName(String rootUserName) {
        Assert.hasText(rootUserName);
        this.rootUserName = rootUserName;
    }

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param securityDAO a not null instance
     */
    @Required public void setSecurityDAO(SecurityDAO securityDAO) {
        Assert.notNull(securityDAO);
        this.securityDAO = securityDAO;
    }

    /**
     * This should be the first task run after the framework tasks.
     *
     * @return APPLICATION_ORDER
     */
    @Override public int order() {
        return APPLICATION_ORDER;
    }

    /**
     * Checks if the root user exists and if not creates one.
     */
    @Override public void execute() {
        if (dao.first(TrackerUser.class) == null) {
            UserImpl root = (UserImpl) securityDAO.findUser(rootUserName);
            if (root != null) {
                TrackerUser user = new TrackerUser();
                user.setSecurityUser(root);
                user.setSex(dao.first(Sex.class));
                dao.create(user);
            }
        }
    }

    /**
     * @return "Generate IWebJtracker root user tasks"
     */
    @Override public String getTaskName() {
        return "Generate IWebJtracker root user tasks";
    }

}
